﻿using UnityEngine;
using System.Collections;

public class interruptor : MonoBehaviour {

	public Transform puerta;
	public bool invertir; 

	public Vector2 angulos; 
	
	public Animator animacion; 
	
	bool moviendose, abierto;

	float anguloGirado;
	float velocity;
	float maxVelocity;
	float inv;
	
	Vector3 pos1, pos2;

	bool staying; 
	bool entering; 

	// Use this for initialization
	void Start () {
		maxVelocity = 600;
		if(invertir) inv = -1;
		else inv = 1;

	

	}
	
	// Update is called once per frame
	void Update () {



		if(moviendose)
		{


			if(abierto)
			{
				velocity = maxVelocity*(100-anguloGirado)/90;
				anguloGirado += Time.deltaTime*velocity;
				if(anguloGirado < 89)
				{
					puerta.RotateAround(puerta.position+puerta.up*puerta.localScale.y/2 ,
				                    	-inv*Vector3.forward ,
					                    Time.deltaTime*velocity);
				}
				else 
				{
					abierto = !abierto;
					moviendose = false;
					puerta.localEulerAngles = new Vector3(angulos.x,puerta.localEulerAngles.y,puerta.localEulerAngles.z);
					if(pos1 == Vector3.zero) pos1 = puerta.position;
					else  puerta.position = pos1;
				}
			}
			else
			{
				velocity = maxVelocity*(100-anguloGirado)/90;
				anguloGirado += Time.deltaTime*velocity;
				if(anguloGirado < 89)
				{
					puerta.RotateAround(puerta.position+puerta.up*puerta.localScale.y/2 ,
				                    	inv*Vector3.forward ,
					                    Time.deltaTime*velocity);
				}
				else 
				{
					puerta.localEulerAngles = new Vector3(angulos.y,puerta.localEulerAngles.y,puerta.localEulerAngles.z);
					abierto = !abierto;
					moviendose = false;
					if(pos2 == Vector3.zero) pos2 = puerta.position;
					else  puerta.position = pos2;
				}
			}
		}
		if(animacion)
		{
			if( (animacion.GetCurrentAnimatorStateInfo(0).normalizedTime >= 1 && animacion.speed > 0) || 
			   (animacion.GetCurrentAnimatorStateInfo(0).normalizedTime <= 0 && animacion.speed < 0) )
			{
				animacion.speed = 0;
			}
		}
		if(staying)
		{
			if(Input.GetButtonDown("Submit"))
			{
				if (!moviendose) 
				{
					anguloGirado = 0;
					moviendose = true; 
					if(!abierto) animacion.speed = 5f;
					else  animacion.speed = -5f;
					animacion.Play("Abrir");
//					animacion.speed = 0;
				}
				else
				{
					anguloGirado = 90-anguloGirado;

					abierto = !abierto;
					if(!abierto) animacion.speed = 5f;
					else  animacion.speed = -5f;

//					animacion.speed = 0;
				}
			}
		}
	
	}

	void OnTriggerStay(Collider obj)
	{
		if(obj.CompareTag("Player1"))
		{
			staying = true;
		}
	}

	void OnTriggerExit(Collider obj)
	{
		if(obj.CompareTag("Player1"))
		{
			staying = false;
		}
	}

}
